package com.ck.controller.admin;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.ck.domain.Admin;
import com.ck.service.AdminService;

public class EditAdminInfoController extends SimpleFormController {

	private AdminService adminService;

	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		Integer adminID = Integer.parseInt(request.getParameter("adminID"));
		Admin admin = adminService.gainAdmin(adminID);
		return admin;
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		Integer adminID = Integer.parseInt(request.getParameter("adminID"));
		Admin admin = (Admin) command;
		admin.setId(adminID);

		Map model = errors.getModel();
		
		//后台校验
        boolean flag = true;
        String email = admin.getEmail().trim();
        
        if( email == null || "".equals(email) ){
        	admin.setEmail(null);
        }else{
	        Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
			Matcher m = p.matcher(email);
			if(!m.matches()){
				model.put("error_email", "email格式不正确");
				flag = false;
			}
        }
		
		if(email.length() > 40){
			model.put("error_email", "email长度：0-40个字符");
			flag = false;
		}
        
		//校验不通过
		if(!flag){
			return new ModelAndView(getFormView(), model);
		}

		boolean isEditAdminInfo = adminService.editAdminInfo(admin);

		if (isEditAdminInfo) {
			return new ModelAndView(getSuccessView());
		} else {
			return new ModelAndView(getFormView(), model);
		}
	}
}
